<template>
	<view @click="alldisbottom" class="" style="overflow: hidden;height: 100vh;">
<!-- 		<view class="chat-top">
			<view class="chat-top-con" style="height: 180upx;" >
				<view class="">
					当前订单：{{orderInfo.create_time || '未知'}}
				</view>
				<view class="">
					订单编号：{{orderInfo.order_sn || '未知'}}
				</view>
				<view class="chat-top-route" @click="seeRoute">
					查看路线
				</view>
			</view>
		</view> -->
		
		<view class="content" >
			<scroll-view class="msg-list p-b-40" 
				scroll-y="true" 
				:scroll-into-view="scrollToView" 
				@scrolltoupper="scrolltoupper"
				style="height: calc(100vh )">
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg-'+index">
					<chat-detail :item="row" @play="playVoice" @openvideo="openvideo"></chat-detail>
				</view>
				<view style="height: 160upx;"></view>
			</scroll-view>
		</view>
		<view class="" v-if="voiceShow" style="position: absolute;z-index:50;bottom: 20%;left: 50%;transform: translate(-50%,0);" >
			<image src="../../static/images/voice_show.png" mode="" style="width: 320upx;height: 60upx;"></image>
		</view>
		
		<view class=" p-l-20 p-r-20 p-t-20 bottom-content"  :style="'height:'+btmheight+'rpx'" style="background-color: #fff;box-shadow: 0upx -2upx 5upx 0upx #ededed;" >
		<!-- 	<view class="flex m-b-20">
				<view class="chat-item"  @click="upImage">
					发图片
				</view>
				<view class="chat-item"  @click="joShow=true">
					发表情
				</view>
				<view class="chat-item" @click="getUserLocation">
					发定位
				</view>
			</view> -->
			
			<view class="flex row-between">
				<view class="m-r-20" @click="chooseType">
					<block v-if="type==1">
					<image style="width: 50rpx;" src="../../static/images/iconPark-voice-message.png" mode="widthFix"></image>
					</block>
					<block v-if="type==2">
						<u-icon name="grid-fill" size="36" > </u-icon>
					</block>
					
				</view>
				<view class="flex-1  send-input m-r-20" v-if="type==1">
					<u-input type="text" v-model="sendInput" maxlength="200" placeholder="请输入您的内容"/>
				</view>
				<view class="flex row-center flex-1  m-r-20 send-voice" v-if="type==2" @touchstart="touchstart"  @touchend="voiceEnd"  style="background-color: #f1f1f1;" >
					{{voiceShow==true?`松开 发送`:`按住 说话`}}
				</view>
				<!-- <view class="m-r-10" >
					<image src="../../static/images/icon_jo.png" mode="" style="width: 52upx;height: 52upx;"></image>
				</view> -->
				<!-- <view class="m-r-10 up-btn"  >
					<u-icon name="map"></u-icon>
				</view> -->
				<view class="up-btn" v-show="!sendInput"  @click.stop="disbottom">
					<u-icon name="plus"></u-icon>
				</view>
				<view class="send-btn" @click.stop="sendMessage" v-show="sendInput">
					发送
				</view>
				
			</view>
			<view class="send-content flex col-center" @click.stop="aa=2" v-show="disbtm">
				<view class="m-l-50" @click.shop="upImageCamera">
					<image style="width:48rpx ;" src="/static/images/st-image.png" mode="widthFix"></image>
			
				<view class="m-t-24"  style="text-align: center;color: #807F7F;" >
					照片
				</view>
				</view>
				<view class="m-l-80" @click.stop="upImage">
					<image style="width:48rpx ;" src="/static/images/st-camera.png" @click="" mode="widthFix"></image>
							
				<view class="m-t-24" style="text-align: center;color: #807F7F;">
					拍摄
				</view>
				</view>
				<view  class="m-l-80" @click.stop="getUserLocation">
					<image style="width:48rpx ;" src="/static/images/ze-location.png" mode="widthFix"></image>
							
				<view class="m-t-24" style="text-align: center;color: #807F7F;">
					位置
				</view>
				
				</view>
				<view  class="m-l-80" @click.stop="upVideo" >
					<image style="width:48rpx ;" src="/static/images/ze-video.png" mode="widthFix"></image>
							
				<view class="m-t-24" style="text-align: center;color: #807F7F;" >
                   视频
				</view>
				
				</view>
			</view>
		</view>
		<u-popup v-model="joShow" mode="bottom"  border-radius="14">
			<scroll-view style="height: 520upx;" scroll-y="true" >
				<view class="flex p-t-20 flex-wrap">
					<view class="men-item m-t-20" v-for="item in memeList" :key="item.id" @click="menSend(item.src)">
						<image :src="item.src" mode="" style="width: 120upx;height: 120upx;" ></image>
					</view>
				</view>
			</scroll-view>
		</u-popup>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	
	innerAudioContext.autoplay = true;
	import {getMemeList,recordList,chatInfo} from '@/api/chat'
	import {
		getOrderDetail
	} from '@/api/order';
	import md5Libs from "@/components/uview-ui/libs/function/md5";
	import {
		baseURL
	} from '@/config/app'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import store from '@/store'
	import GDMap  from '@/js_sdk/amap-wx/amap-wx.130'
	
	export default {
		data() {
			return {
				aa:1,
				btmheight:"130",
				disbtm:false,
				memeList:[],
				im_id:null,
				order_id:null,
				user_id:null,
				sendInput:'',
				scrollToView:'',
				msgList:[],
				page:1,
				// 1文字 2语音
				type:1,
				voicePath:'',
				count:null,
				isScroll:true,
				joShow:false,
				voiceShow:false,
				setTime:null,
				time:0,
				dgMap:'',
				orderInfo:{},
				addressList:[],
				drname:"",
			}
		},
		watch:{
			'msgList.length':function(value){
				if(this.isScroll){
					console.log(value);
					this.$nextTick(function(){
						this.scrollToView = 'msg-' + (value*1-1)
					})
				}
				
				console.log(this.scrollToView)
			},
			voiceShow(val){
				if(val){
					
				}
			}
		},
		methods: {
			//调用播放视频组件
			openvideo(item){
			
				 uni.setStorageSync('video',item);
				uni.navigateTo({
					url:"/bundle/pages/open_video/open_video"
				})
				
			},
			//展示下面部分代码
			alldisbottom(){
				this.btmheight="130"
				this.disbtm=false
			}, 
			disbottom(){
			 if(this.disbtm==false){
				 this.btmheight="340"
				 this.disbtm=true
				 uni.hideKeyboard()
			 }else{
				 this.btmheight="130"
				 this.disbtm=false
			 }
			},
			getUserLocation(){
				var _this=this
					uni.chooseLocation({
								    success: function (res) {
									var latitude = res.latitude
											var longitude = res.longitude
											_this.sendAddress(longitude,latitude)
								     
								    }
								
								})
				// uni.getLocation({
				// 	type: 'gcj02',
				// 	 success:res=>{
				// 		var latitude = res.latitude
				// 		var longitude = res.longitude
				// 		this.sendAddress(longitude,latitude)
						
				// 	},
				// 	fail:err=>{
				// 		this.$toast({
				// 			title:'请先授权或者开启定位'
				// 		})
				// 		console.log('用户未开启授权');
				// 	}
				// })
			},
			succMap(longitude,latitude){
				return new Promise((resolve, reject)=>{
					this.mapgd.getRegeo({
						 location:`${longitude},${latitude}`,
						 success:res=>{
							resolve(res);
						 },
						 fail:err=>{
							 reject(err)
							 console.log(err);
							 console.log('未识别到用户位置')
						 }
					})
				})
			},
			
			async sendAddress(longitude,latitude){
				const address =  await this.succMap(longitude,latitude);
				console.log(address);
				
				let result = {
					latitude:address[0].latitude,
					longitude:address[0].longitude,
					name:address[0].name,
					detail:address[0].desc
				}
				let message = JSON.stringify(result)
				let num = this.userInfo.avatar.indexOf('uploads')
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message,
					is_send:true,
					type:6,
					avatar: this.userInfo.avatar.slice(num)
				}
				console.log(data)
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.msgList.push(data)
						this.alldisbottom()
					}
				})
				
			},
			menSend(message){
				
				let num = this.userInfo.avatar.indexOf('uploads')
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message,
					is_send:true,
					type:4,
					avatar: this.userInfo.avatar.slice(num)
				}
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.isScroll = true;
						this.joShow = false;
						console.log(res)
						this.$toast({
							title:'发送成功'
						})
						this.sendInput = '';
						this.msgList.push(data)
					}
				})
			},
			chooseType(){
				this.btmheight="130"
				this.disbtm=false
				
				if(this.type==1){
					this.type = 2;
					return 
				}
				if(this.type==2){
					this.type = 1;
					
				}
			},
			playVoice(message) {
				console.log('播放录音');
				console.log(message)
				console.log(this.$u.test.jsonString(message))
				let res = '';
				if(this.$u.test.jsonString(message)){
					let json = JSON.parse(message)
					console.log(json)
					res = json.url
				}
				else{
					res = message
				}
				console.log(res)
				
				if (res) {
					innerAudioContext.src = res;
					innerAudioContext.play();
				}
			},
			getAuto(){
				var _this = this;
				uni.authorize({
					scope:'scope.record',
					success:res=>{
						console.log(res);
						this.touchstart();
					},
					fail:err=>{
						uni.showModal({
							title:'提示',
							content:'是否开启语音功能，发送语音更方便',
							success:res=>{
								if(res.confirm){
									uni.openSetting({
									  success(res) {
									    console.log(res.authSetting)
										
									  }
									});
								}
								
							}
						})
					}
				})
			},
			touchstart(){
				this.voiceShow = true;
				console.log('手指触摸')
				
				this.setTime = setInterval(()=>{
					this.time = this.time + 1
				},1000)
				
				recorderManager.start({
					format:'mp3'
				});
			},
			voiceEnd(){
				this.voiceShow = false;
				console.log('触摸结束')
				recorderManager.stop();
				clearInterval(this.setTime)
			},
			// 
			scrolltoupper(){
				this.getRecordListFun();
			},
			sendMessage(){
				if(!this.sendInput){
					this.$toast({
						title:'请输入要发送的内容'
					})
					return 
				}
				console.log(this.userInfo)
				let num = this.userInfo.avatar.indexOf('uploads')
				
				
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message:this.sendInput,
					type:1,
					is_send:true,
					avatar: this.userInfo.avatar.slice(num)
				}
				
				console.log(data);
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.isScroll = true;
						console.log(res)
						this.$toast({
							title:'发送成功'
						})
						this.sendInput = '';
						this.msgList.push(data)
						
					}
				})
			},
			//上传视频
			upVideo(){
				let _this=this
				console.log(312123);
				uni.chooseVideo({
					sourceType:['album',"camera"],
					success:res=>{
					
						let filePath = res.tempFilePath;
						uni.uploadFile({
							url: baseURL + '/api/file/formimage',
							filePath,
							name: 'file',
							header: {
								token: store.getters.token,
							    // version: '1.2.1.20210717'
							},
							header:{
								token: store.getters.token
							},
							success: (uploadFileRes) => {
								
								const result = JSON.parse(uploadFileRes.data)
								console.log(result)
								const url = result.data.uri
								_this.videoSocket(url);
							}
						});
					}
				})
			},
			upImageCamera(){
				var _this = this;
				uni.chooseImage({
					sourceType:["album"],
					count:1,
					success:res=>{
						console.log(res);
						let filePath = res.tempFilePaths[0];
						uni.uploadFile({
							url: baseURL + '/api/file/formimage',
							filePath,
							name: 'file',
							header: {
								token: store.getters.token,
							    // version: '1.2.1.20210717'
							},
							header:{
								token: store.getters.token
							},
							success: (uploadFileRes) => {
								
								const result = JSON.parse(uploadFileRes.data)
								console.log(result)
								const url = result.data.uri
								_this.imgSocket(url);
							}
						});
					}
					
				})
			},
			
			upImage(){
				var _this = this;
				uni.chooseImage({
					sourceType:["camera"],
					count:1,
					success:res=>{
						console.log(res);
						let filePath = res.tempFilePaths[0];
						uni.uploadFile({
							url: baseURL + '/api/file/formimage',
							filePath,
							name: 'file',
							header: {
								token: store.getters.token,
							    // version: '1.2.1.20210717'
							},
							header:{
								token: store.getters.token
							},
							success: (uploadFileRes) => {
								
								const result = JSON.parse(uploadFileRes.data)
								console.log(result)
								const url = result.data.uri
								_this.imgSocket(url);
							}
						});
					}
					
				})
			},
			videoSocket(url){
				
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message:url,
					type:3,
				}
				if(this.im_id==undefined){
					this.$toast({
						title:'获取房间号错误'
					})
					return 
				}
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.isScroll = true;
						console.log(this.msgList)
						let num = this.userInfo.avatar.indexOf('uploads')
						this.msgList.push({
							im_id:this.im_id,
							user_id:this.user_id,
							sn:this.getMd5,
							message:url,
							type:3,
							is_send:true,
							avatar:this.userInfo.avatar.slice(num)
						
						})
							this.alldisbottom()
						setTimeout(()=>{
							
						},3000)
					}
			})
			},
			imgSocket(url){
				console.log(url);
				
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message:url,
					type:2,
				}
				if(this.im_id==undefined){
					this.$toast({
						title:'获取房间号错误'
					})
					return 
				}
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.isScroll = true;
						console.log(this.msgList)
						let num = this.userInfo.avatar.indexOf('uploads')
						this.msgList.push({
							im_id:this.im_id,
							user_id:this.user_id,
							sn:this.getMd5,
							message:url,
							type:2,
							is_send:true,
							avatar:this.userInfo.avatar.slice(num)
						
						})
							this.alldisbottom()
						setTimeout(()=>{
							
						},3000)
					}
				})
			},
			websocketInit(){
				let url = 'wss://hy.qslmkj.com:9801';
				this.websocket = uni.connectSocket({
					url,
					success:res=>{
						console.log(res)
					},
					fail:err=>{
						console.log(err)
					}
				})
				this.websocket.onOpen(res=>{
					this.openSocket = true;
					this.websocket.onMessage(res=>{
						console.log(res);
						let result = JSON.parse(res.data);
						console.log(result)
						if(result.code==100){
							this.$toast({
								title:result.msg
							})
						}
						if(result.code==202){
							this.im_id = result.data.im_id
							this.getRecordListFun();
						}
						if(result.code==203){
							setTimeout(()=>{
								this.msgList.find((item)=>{
									if(item.sn = result.data.sn){
										item.is_send = false;
										this.$forceUpdate();
									}
								})
							},1500)
						}
						if(result.code==204){
							console.log(result)
							let data = result.data
							let obj = {
								message:data.message,
								avatar:data.target_info.avatar,
								type:data.type
							}
							this.msgList.push(obj)
						}
						
					})
					let data = {
						im_id:this.im_id,
						// order_id:this.order_id,
						user_id:this.user_id
					}
					
					console.log(JSON.stringify(data))
					this.websocket.send({
						data:JSON.stringify(data),
						success:res=>{
							console.log(res)
						},
						fail:err=>{
							// console.log('房间创建或者加入失败，请')
							this.$toast({
								title:err
							})
						}
					})
				})
			},
			getMemeListFun(){
				getMemeList().then(res=>{
					this.memeList = res.data.lists
				})
			},
			getRecordListFun(){
				if(this.count==this.msgList.length){
					this.$toast({
						title:'没有更多了'
					})
					return 
				}
				
				
				recordList({
					id:this.im_id,
					page:this.page,
					limit:12
				}).then(res=>{
					
					if(this.page>1){
						this.isScroll = false;
					}
					this.msgList.unshift(...res.data.lists) ;
					this.count = res.data.count
					this.page = this.page + 1;
				})
			},
			sendVoice(url){
				let {time} = this;
				if(time<=1){
					this.$toast({
						title:"录制时间过短"
					})
					return 
				}
				
				
				
				let num = this.userInfo.avatar.indexOf('uploads')
				
				let message = {
					url,
					time
				}
				
				let data = {
					im_id:this.im_id,
					user_id:this.user_id,
					sn:this.getMd5,
					message:JSON.stringify(message),
					avatar: this.userInfo.avatar.slice(num),
					type:5,
					is_send:true,
				}
				console.log(data);
				
				this.websocket.send({
					data:JSON.stringify(data),
					success:res=>{
						this.isScroll = true;
						console.log(res);
						this.msgList.push(data)
						this.time = 0
						this.alldisbottom()
					}
					
				})
			},
			upVoice(path){
				console.log(path)
				uni.uploadFile({
					url:baseURL + '/api/file/video',
					name:'file',
					filePath:path,
					header: {
						token: store.getters.token,
					    // version: '1.2.1.20210717'
					},
					success:res=>{
						let data = JSON.parse(res.data);
						console.log(data);
						if(data.code==1){
							this.sendVoice(data.data.uri)
						}
					},
					fail:err=>{
						console.log(err)
					}
				})
			},
			getOrderDetailFun() {
				getOrderDetail({id:this.order_id}).then(res => {
					console.log(res)
					this.orderInfo = res.data;
					this.initAddress();
				});
			},
			initAddress(){
				let arr = this.orderInfo.address.concat();
	
				// if(this.addressFlag==false){
				// 	return 
				// }
				arr.forEach((item,index)=>{
					if(index==arr.length-1){
						let obj1 = {
							name:arr[index].start_address,
							longitude:arr[index].start_longitude,
							latitude:arr[index].start_latitude,
						};
						let obj2 = {
							name:arr[index].end_address,
							longitude:arr[index].end_longitude,
							latitude:arr[index].end_latitude,
						}
						this.addressList.push(obj1)
						this.addressList.push(obj2)
					}
					else{
						let obj = {
							name:arr[index].start_address,
							longitude:arr[index].start_longitude,
							latitude:arr[index].start_latitude,
						};
						this.addressList.push(obj)
					}
				})
				this.addressFlag = false
			},
			seeRoute(){
				let arr = this.addressList
				console.log(this.addressList);
				let origin = arr[0].longitude + ',' + arr[0].latitude
				let destination = arr[arr.length-1].longitude + ',' + arr[arr.length-1].latitude
				uni.navigateTo({
					url:'/bundle/pages/map/map?origin=' + origin +  '&destination=' + destination
				})
			}
		},
		beforeDestroy() {
			uni.closeSocket({})
		},
		onLoad(option) {
			this.mapgd =  new GDMap.AMapWX({key:'364c1096e6b21c6e94ffaf5cc02e4d08'});
			let self = this;
			recorderManager.onStop(function (res) {
			    console.log('recorder stop' + JSON.stringify(res));
			    self.voicePath = res.tempFilePath;
				self.upVoice(res.tempFilePath)
			}); 
	
		
			let {order_id,user_id,im_id,dr_name} = option;
			this.order_id = order_id;
			this.user_id = this.userInfo.id;
			this.im_id = im_id;
			this.drname=dr_name
			
			
            uni.setNavigationBarTitle({
            	title:this.drname
            })
			
			this.getMemeListFun();
			this.getOrderDetailFun();
			this.websocketInit()

		},
		computed:{
			...mapGetters(["userInfo"]),
			getMd5(){
				let date = new Date();
				console.log()
				let time = date.getTime()
				let user_id = this.user_id
				// let id = UserInfo.id
				let md5 = `${time},${user_id}`
				console.log(md5)
				return md5Libs.md5(md5)
			}
		}
	}
</script>

<style scoped lang="scss">
	.send-content{
		width: 100%;
		border-top: 2rpx solid #F0EFEF;
		margin-top: 20rpx;
		height: 204rpx;
		
	}
	.bottom-content{

		width: 100%;
		position: fixed;
		bottom: 0rpx;
	}
	.chat-top{
		padding: 20upx 30upx;
		.chat-top-con{
			position: relative;
			display: flex;
			flex-direction: column;
			justify-content: center;
			padding: 10upx 20upx;
			background-color: rgb(84,86,101);
			color: #fff;
			border-radius: 20upx;
			view{
				&:first-child{
					padding-bottom: 20upx;
				}
			}
			.chat-top-route{
				position: absolute;
				top: 30upx;
				right: 20upx;
				border: 1upx solid;
				border-radius: 100upx;
				padding: 10upx 20upx;
			}
		}
		
	}
	.chat-item{
		margin-right: 10upx;
		padding: 0upx 30upx;
		border-radius:500upx;
		border: 1upx solid $-color-primary;
		color: $-color-primary;
		font-weight: bold;
	}
	.send-btn{
		background-color: $-color-primary;
		padding: 10upx 20upx;
		color: #fff;
		border-radius: 20upx;
	}
	.send-input{
		border-radius: 20upx;
		padding: 10upx 20upx;
		background-color: #eee;
	}
	.send-voice{
		padding: 10upx 20upx;
		// color: #;
	}
	.up-btn{
		background-color: #fff;
		padding: 12upx;
		border-radius: 50%;
		border: 1upx solid  #f1f1f1;
		background-color: #f1f1f1;
	}
	.content{
		padding: 0 20upx;
	}
	.men-item{
		flex: 0 0 25%;
		text-align: center;
	}
</style>
